<?php

class EventController extends BaseController {
        
    public function indexAction($requestData) {
    	$event = $this->getEventThroughArg($requestData['arg0']);
    	if(!$event) {
    		BaseController::redirect("../");
    		return;
    	}
    	
    	if(isset($requestData['submit'])) {
			BaseController::forward("Event", "post_commentAction");
	    	EventController::post_commentAction($requestData);
	    	return;
    	}
    	
    	$this->data['pageTitle'] = $event->name . ' - Peak 100';
    	
		$this->data['event'] = $event;
		$this->data['event']->comments = p1_event_comment::getAll(array('event'=>$this->data['event']->id), array('id', 'ASC'));
		$this->data['event']->details = p1_event_detail::get($this->data['event']->id, "event");
		$this->data['event']->sports = pk_sport::toSportNames($this->data['event']->sports);
		
		$location = array($this->data['event']->details->location);
		$location[] = $this->data['event']->details->city;
		$location[] = $this->data['event']->details->state;
		$location[] = $this->data['event']->details->country;
		$count = 0;
		foreach($location as $l) {
			if(trim($l) == '') {
				unset($location[$count]);
			}
			$count++;
		}
		$this->data['event']->location = implode(', ', $location);
    	
		$this->data['events'] = p1_event::getAll();
    }
    
    private function getEventThroughArg($arg) {
    	$event = isset($arg) ? $arg : "";
    	if($event == "") {
    		return false;
    	}
    	$event = p1_event::get(addslashes(seourl($arg)), "name");
    	if(!$event->exists()) {
    		return false;
    	}
    	return $event;
    }
    
    public function post_commentAction($requestData) {
    	$event = $this->getEventThroughArg($requestData['arg0']);
    	if(!$event) {
    		BaseController::redirect("../");
    		return;
    	}
    	
    	$comment = new p1_event_comment($requestData);
    	$comment->event = $event->id;    	
    	$validation = $comment->validate();    
		if(!CaptchaController::validateCaptcha($requestData['security_code'])) {
			$message = 'Please enter correct security code.';
			if(is_array($validation))
				$validation[] = $message;
			else $validation = array($message);
		}
		if(is_array($validation)) {
			$this->data['errors'] = $validation;
			BaseController::forward("Event", "index");
			unset($requestData['submit']);
			
	    	EventController::indexAction($requestData);
		} else {
			$comment->save();
			// save cookies here
			
	    	setcookie("p1c_name", $requestData['name'], time() + (2*24*60*60), "/", str_replace('www', '', $_SERVER['SERVER_NAME']));
	    	
			BaseController::redirect('../event/'. seourl($event->name, true) . "/");
		}
    }

}

?>